package gov.pbc.nn.kjgl.maintenance.view;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.core.dao.CommonJdbcDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.utils.EntityRowMapperUtils;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.maintenance.entity.SysChange;
import gov.pbc.nn.kjgl.maintenance.entity.SysChangeContent;
import gov.pbc.nn.kjgl.maintenance.entity.SysEmergencyScheme;
import gov.pbc.nn.kjgl.maintenance.entity.SysMaterial;
import gov.pbc.nn.uflo.entity.Opinion;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.ParseResult;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;
import com.bstek.uflo.client.service.ProcessClient;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.service.StartProcessInfo;
import com.bstek.uflo.service.TaskOpinion;

/**
 * 
 * @author jack.zhao 系统变更内容操作表，数据库加业务逻辑
 */
@Component
public class SysChangeContentPR {

	@Resource(name = CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao hibernateDao;

	@Resource(name = CommonJdbcDao.BEAN_ID)
	private CommonJdbcDao jdbcDao;

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao coreHibernateDao;

	@Autowired
	@Qualifier(ProcessClient.BEAN_ID)
	private ProcessClient processClient;

	@Autowired
	@Qualifier(TaskClient.BEAN_ID)
	private TaskClient taskClient;

	/**
	 * 查出所有状态等于10的记录，并且分页 0:初始；5：审核中；10：审核通过；15：审核未通过；20：撤消
	 * 
	 * @auther jack.zhao
	 * @param page
	 * @param criteria
	 * 
	 */
	@DataProvider
	public void loadSysChange(Page<SysChange> page, Criteria criteria) {
		/*DetachedCriteria dc = this.hibernateDao.buildDetachedCriteria(criteria, SysChange.class);
		dc.add(Restrictions.eq("invalid", false));
		dc.add(Restrictions.eq("state", 10));
		// dc.add(Restrictions.eq("deptId",
		// ContextHolder.getLoginUser().getDepts().get(0).getId()));
		this.hibernateDao.pagingQuery(page, dc);
		*/
		Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		String sql = "select a.* from T_SYS_CHANGE as a  where a.INVALID_=0 and a.STATE_=10 and "
				+ " a.sys_id_ in (select s.id_ from T_SYS_ENTITY as s where s.INVALID_=0 and  s.OPERATION_DEPT_ID_=:deptId) "
				+ " order by a.CREATE_DATE_";
		Map<String, Object> map = new HashMap<String, Object>();
		ParseResult pr = jdbcDao.parseCriteria(criteria, true, "a");
		map.put("deptId", dept.getCDept().getId());
		if (pr != null) {
			StringBuffer sbSql = pr.getAssemblySql();
			sql += " and " + sbSql;
			map.putAll(pr.getValueMap());
		}
		this.jdbcDao.pagingQuery(page, sql, new RowMapper<SysChange>() {
			@Override
			public SysChange mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				SysChange sp = EntityRowMapperUtils.get(SysChange.class, rs, rowNum);
				try {
					sp = EntityUtils.toEntity(sp);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return sp;

			}
		}, map);
	}

	/**
	 * 根据id查找内容的值
	 * 
	 * @auther jack.zhao
	 * @param id
	 * @return
	 * 
	 */
	@DataProvider
	public SysChangeContent getChangeContent(String id) {
		String sql = "from SysChangeContent where changeID=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<SysChangeContent> query = this.hibernateDao.query(sql, map);
		if (query.size() > 0) {
			return query.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 更新SysChangeContent实体的值
	 * 
	 * @auther jack.zhao
	 * @param content
	 * @param parameter
	 * 
	 */
	@DataResolver
	@Transactional
	public void saveSysChangeContent(SysChangeContent content, Map<String, Object> parameter) {
		String changeId = (String) parameter.get("changeId");
		content.setChangeID(changeId);
		this.saveAll(content);

	}

	/**
	 * 根据状态更新内容实体
	 * 
	 * @auther jack.zhao
	 * @param content
	 * 
	 */
	public void saveAll(SysChangeContent content) {
		String id = content.getId();
		if (StringUtils.isEmpty(id)) {
			this.hibernateDao.save(content);
		} else {
			this.hibernateDao.update(content);
		}
	}

	/**
	 * ajax接口，传入对应的参数，开启流程
	 * 
	 * @auther jack.zhao
	 * @param parameter
	 * @throws Exception
	 * 
	 */
	@Expose
	@Transactional
	public void startProcess(Map<String, Object> parameter) throws Exception {
		String businessId = (String) parameter.get("id");
		String contentId = (String) parameter.get("contentId");
		String sysId = (String) parameter.get("sysId");
		// 改变状态
		this.changeState(contentId, 1);
		// 开始流程
		SysChange syschange = this.hibernateDao.get(businessId, SysChange.class);

		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("sysId", sysId);
		variables.put("sysName", syschange.getSysName());
		StartProcessInfo info = new StartProcessInfo();
		info.setPromoter(ContextHolder.getLoginUserName());
		info.setCompleteStartTask(true);
		info.setVariables(variables);
		info.setBusinessId(businessId);
		processClient.startProcessByName("系统变更记录", info);
	}

	/**
	 * 保存并且提交
	 * 
	 * @auther jack.zhao
	 * @param content
	 * @param parameter
	 * @throws Exception
	 * 
	 */
	@DataResolver
	@Transactional
	public void updateAndTj(SysChangeContent content, Map<String, Object> parameter) throws Exception {
		String changeId = (String) parameter.get("id");
		content.setChangeID(changeId);
		this.saveAll(content);
		// 开启流程需要的id
		parameter.put("contentId", content.getId());
		// 开启流程
		this.startProcess(parameter);
	}

	/**
	 * 传入Id，和需要变更的状态来改变状态
	 * 
	 * @auther jack.zhao
	 * @param id
	 * @param state
	 * 
	 */
	// 0：初始状态，1：提交状态：2：回退状态
	public void changeState(String id, int state) {
		SysChangeContent content = this.hibernateDao.get(id, SysChangeContent.class);
		content.setState(state);
		this.hibernateDao.update(content);
	}

	/**
	 * 审核ajax适用于驳回和同意
	 * 
	 * @auther jack.zhao
	 * @param taskId
	 * @param opinion
	 * @param button
	 * @param contentId
	 * 
	 */
	@Expose
	@Transactional
	public void ajaxShenHe(String taskId, String opinion, String button, String contentId) {
		TaskOpinion option = new TaskOpinion(opinion);
		Task task = taskClient.getTask(Long.valueOf(taskId));
		taskClient.start(Long.valueOf(taskId));
		final Opinion o = new Opinion();
		o.setOpinion(opinion);
		o.setNodeName(task.getNodeName());
		o.setBusKey(task.getBusinessId());
		o.setTaskId(Long.parseLong(taskId));
		o.setBusTable("T_SYS_CHANGE_CONTENT");
		o.setTaskName(task.getTaskName());
		o.setNodeName(task.getNodeName());
		o.setProcessName("系统变更记录");
		o.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
		o.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
		o.setUsername(ContextHolder.getLoginUserName());
		o.setCname(ContextHolder.getLoginUser().getCname());
		// this.applyEntryDao.save(o);
		this.coreHibernateDao.save(o);

		if (button.equals("ok")) {
			taskClient.complete(Long.valueOf(taskId), "结束", option);
		} else {
			taskClient.complete(Long.valueOf(taskId), "驳回", option);
			this.changeState(contentId, 2);
		}
	}

	/**
	 * 再次提交
	 * 
	 * @auther jack.zhao
	 * @param taskId
	 * 
	 */
	@Expose
	@Transactional
	public void ajaxReStart(Map<String, Object> parameter) {
		String taskId = (String) parameter.get("taskId");
		String contentId = (String) parameter.get("contentId");
		this.changeState(contentId, 1);
		taskClient.start(Long.valueOf(taskId));
		taskClient.complete(Long.valueOf(taskId));
	}

	/**
	 * 根据主表的id得到单个主表
	 * 
	 * @auther jack.zhao
	 * @param bussinessId
	 * @return
	 * 
	 */
	@DataProvider
	public SysChange getSysChange(String bussinessId) {
		return this.hibernateDao.get(bussinessId, SysChange.class);
	}

	@DataProvider
	public String getMaterialFileName(String id) {
		if (id != null) {
			return this.hibernateDao.get(id, SysMaterial.class).getFileName();
		}
		return null;
	}
}
